/*
 * @Author: 张仁会 28396543@qq.com
 * @Date: 2022-09-11 18:35:11
 * @LastEditors: 张仁会 28396543@qq.com
 * @LastEditTime: 2022-09-11 20:30:05
 * @FilePath: \react-app\src\components\aa\aa.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import React, { useEffect, useState } from 'react';

export default function Count(props) {
  const [n, setN] = useState(props.num || 10)
  function useCountDown() {
    const changeCount = (n) => {
      const timer = setTimeout(() => {
        const current = --n; // n-- 值还是10未变 --n值为9改变
        setN(current)
      }, 1000);
      return timer;
    }

    // 监听状态变化
    useEffect(() => {
      const timer = changeCount(n);
      if (n === 0) {
        setN(0);
        clearTimeout(timer);
      }
      return () => {
        clearTimeout(timer);
      }
    }, [n])
    return { n };
  }
  function Timer(n) {
    const { n: time } = useCountDown(n)
    return <span>{time === 0 ? <p onClick={() => {
      setN(props.num)
    }}>开始</p> : <p>剩余{time}秒</p>}</span>
  }
  return (
    <div>
      <Timer />
    </div>
  );
}